package com.project.market.controller;

import com.project.market.bo.AddGoodsBo;
import com.project.market.db.domain.MarketGoods;
import com.project.market.db.domain.MarketGoodsAttribute;
import com.project.market.db.domain.MarketGoodsProduct;
import com.project.market.db.domain.MarketGoodsSpecification;
import com.project.market.service.AdminGoodsService;
import com.project.market.service.impl.AdminGoodsServiceImpl;
import com.project.market.util.JacksonUtil;
import com.project.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/goods/*")
public class AdminGoodsController extends HttpServlet {

    //每个功能模块创建一个controller、一个service
    private AdminGoodsService goodsService = new AdminGoodsServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //首先进行分发
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/goods/", "");
        if ("list".equals(op)) {
            list(req, resp);
        } else if ("catAndBrand".equals(op)) {
            catAndBrand(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/goods/", "");
        if ("create".equals(op)) {
            create(req, resp);
        }
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1. 接收请求参数信息
        //需要新建一个对象，叫做Bo
        //将传输过来的数据转换成字符串
        String requestBody = req.getReader().readLine();
        ObjectMapper objectMapper = JacksonUtil.getMapper();
        AddGoodsBo addGoodsBo = objectMapper.readValue(requestBody, AddGoodsBo.class);
        List<MarketGoodsProduct> products = addGoodsBo.getProducts();
        MarketGoods goods = addGoodsBo.getGoods();
        List<MarketGoodsSpecification> specifications = addGoodsBo.getSpecifications();
        List<MarketGoodsAttribute> attributes = addGoodsBo.getAttributes();
        Object re = goodsService.create(goods, products, specifications, attributes);
        if (re == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(401,"参数不对")));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
        }
    }

    /**
     * 用来去查询当前系统的品牌商以及商品的分类信息，用来进行渲染商品上架的页面
     *
     * @param req
     * @param resp
     */
    private void catAndBrand(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> result = goodsService.catAndBrand();
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(result)));
    }

    /**
     * 展示商品的列表信息
     * 1.接收参数
     * 2.处理业务逻辑
     * 3.返回结果
     *
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        //商品编号
        String goodsSn = req.getParameter("goodsSn");
        //商品名称
        String name = req.getParameter("name");
        //也可以做一些设置，比如设置默认排序规则
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        //用户可能自己复制了地址，手动修改了goodsId的值，输入了abc，后续处理的时候，就会出错
        String goodsId = req.getParameter("goodsId");
        try {
            //用户传递过来的goodsId如果是abc，则被catch捕获
            if (!StringUtils.isEmpty(goodsId)) {
                Integer.parseInt(goodsId);
            }
        } catch (Exception e) {
            //TODO
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }
        //后续写显示的业务逻辑-----service层去做
        List<MarketGoods> goodsList = goodsService.list(page, limit, goodsSn, name, sort, order, goodsId);
        Object o = ResponseUtil.okList(goodsList);
        resp.getWriter().println(JacksonUtil.writeValueAsString(o));
    }
}
